<template>
  <div>
    <el-button
      type="danger"
      @click="addDomain"
      :icon="Plus"
      style="float: left; margin-left: 10px; width: 100px; height: 40px"
      >新增</el-button
    >&emsp;
    <el-button
      :disabled="!buttonDisable"
      type="danger"
      @click="allDomain()"
      :icon="Check"
      style="float: left; margin-left: 25px; width: 100px; height: 40px"
      >保存</el-button
    >&emsp;
    <el-button
      :disabled="!buttonDisable"
      type="danger"
      @click="delDomain"
      :icon="Back"
      style="float: left; margin-left: 25px; width: 100px; height: 40px"
      >撤销</el-button
    >&emsp;
    <el-button
      :disabled="!buttonDisable"
      type="danger"
      @click="delDomains"
      :icon="Delete"
      style="float: left; margin-left: 25px; width: 100px; height: 40px"
      >删除</el-button
    >
  </div>
  <br />

  <div style="font-size: 22px">
    期初日期：<el-date-picker
      v-model="ProDates"
      type="date"
      placeholder="Pick a date"
      :default-value="new Date()"
      style="width: 200px"
    />
    &nbsp;&nbsp; &nbsp;&nbsp; 单据号：<el-input
      v-model="proCodes"
      style="width: 200px"
      disabled
    >
    </el-input>
    &nbsp;&nbsp; &nbsp;&nbsp; 流水号：
    <el-input v-model="weater" style="width: 200px" disabled> </el-input>
  </div>

  <br /><br />
  <hr style="font-size: 20px" />
  <br />

  <div class="table-container" style="height: 400px; position: relative">
    <table style="border-collapse: collapse">
      <tr>
        <td>序号</td>
        <td>耳号</td>
        <td>栋舍</td>
        <td>栏位</td>
        <td>只数</td>
        <td>重量(公斤)</td>
      </tr>
      <tr v-for="(ruleForm, index) in loge.healthArray">
        <td>
          {{ ruleForm.indexNumber }}
        </td>
        <td>
          <el-select
            v-model="ruleForm.sleepInforId"
            placeholder="耳号"
            style="width: 150px"
          >
            <el-option
              v-for="item in sleepInfoDatas.filter((c:any)=>c.stayStatus==0&&c.sleepTypeId==1)"
              :label="item.earNumber"
              :value="item.sleepInforId"
            />
          </el-select>
        </td>
        <td>
          <el-select
            style="width: 120px"
            v-model="ruleForm.cottagesId"
            placeholder="所在栋舍"
            @change="getFields(ruleForm.cottagesId, index)"
            clearable
          >
            <el-option
              v-for="item in cottagesDatas"
              :label="item.cottageName"
              :value="item.cottagesId"
            />
          </el-select>
        </td>
        <td>
          <el-select
            v-model="ruleForm.field"
            placeholder="所在栏位"
            clearable
            style="width: 100px"
          >
            <el-option
              v-for="item in fieldsDatas[index]"
              :label="item.fieIdName"
              :value="item.fieIdId"
            />
          </el-select>
        </td>
        <td>
          {{ ruleForm.maleBeginSum }}
        </td>
        <td style="width: 200px">
          <el-input
            v-model="ruleForm.maleBeginWeight"
            style="width: 180px; text-align: center"
            oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
            placeholder="请输入数字(小数点后两位)"
            class="center-input"
          ></el-input>
        </td>
        <!-- <td>
        <el-button type="success" :icon="Check" circle  @click="inithealth(index)" />
        <el-button type="danger" :icon="Delete" circle @click.prevent="beginDel(index)"/>
      </td> -->
      </tr>
    </table>
  </div>
  <div style="bottom: 0; left: 0; width: 100%">
    <hr />
    <!-- <span>&emsp; 合计</span>
            <hr> -->
    <el-button
      link
      type="danger"
      :icon="Plus"
      style="float: left; margin-left: 10px"
      @click="addDomain"
      >增行</el-button
    >&emsp;
    <el-button
      link
      type="danger"
      :icon="Minus"
      style="float: left; margin-left: 10px"
      @click="delDomain"
      >删行</el-button
    >&emsp;
    <br />
    <hr />
    <span style="vertical-align: top; width: 5%">&emsp; 备注</span>&emsp;
    <el-input type="textarea" style="width: 85%" placeholder="请输入备注信息" />
  </div>
</template>

<script setup lang="ts">
import {
  Check,
  Delete,
  Edit,
  Message,
  Back,
  Plus,
  Setting,
  SuccessFilled,
  Minus,
  Close,
} from '@element-plus/icons-vue';
import { reactive, ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useCounterStore } from '@/stores/counter';

const counterStore = useCounterStore();
const route = useRoute();
const router = useRouter();
//获取雪花id(单据号、流水号)
const getIds1 = () => {
  axios
    .post('http://localhost:5039/api/ProductionManagement/GetId', {})
    .then((res) => {
      proCodes.value = res.data;
      //第一条单据号（需要单独赋值）
      loge.healthArray[0].maleCode = JSON.stringify(res.data);
      console.log('11111111');
      console.log(loge.healthArray)
    });
};

//流水号
const weater = ref('');

const getIds2 = () => {
  axios
    .post('http://localhost:5039/api/ProductionManagement/GetId', {})
    .then((res) => {
      weater.value = res.data;
    });
};

//期初日期
const ProDates =ref(new Date());

//单号
const proCodes = ref('');

//序号
const numbers = ref(1);
const loge = reactive({
  healthArray: <any>[
    reactive({
      indexNumber: numbers.value,
      maleCode: '',
      maleData: ProDates.value,
      sleepInforId: '',
      cottagesId: '',
      field: '',
      maleBeginSum: 1,
      maleBeginWeight: '',
      createId: counterStore.employeeId,
      deletes: false,
    }),
  ],
});

//按钮禁用条件
const buttonDisable = computed(() => {
  return loge.healthArray.length > 0;
});
//增行
const addDomain = () => {
  loge.healthArray.push(
    reactive({
      indexNumber: loge.healthArray.length + numbers.value,
      maleCode: JSON.stringify(proCodes.value),
      maleData: ProDates,
      sleepInforId: '',
      cottagesId: '',
      field: '',
      maleBeginSum: 1,
      maleBeginWeight: '',
      createId: counterStore.employeeId,
      deletes: false,
      createTime: new Date(),
    })
  );
  console.log(loge.healthArray);
};

//减行
const delDomain = () => {
  loge.healthArray.splice(loge.healthArray.length - 1, 1);
};

//保存
// const inithealth = (index: number) => {
//   console.log(loge.healthArray[index])

//   axios.post("http://localhost:5039/api/SleepBegin/AddProBegin",  loge.healthArray[index]).then(res => {
//     if (res.data.code > 0) {
//       ElMessage.success('后裔期初信息添加成功');
//       getIds1();
//       getIds2();
//     } else {
//       ElMessage.error('后裔期初信息添加失败，再试试。。。')
//     }
//   })

//    loge.healthArray.splice(index,1)

// };
//移除
// const beginDel = (index:any) => {
//   loge.healthArray.splice(index, 1)
//   numbers.value++;
// }

//删除
const delDomains = () => {
  loge.healthArray.splice(0, loge.healthArray.length);
  numbers.value = 1;
};

//获取栋舍信息
const cottagesDatas: any = ref([]);
const getCottages = () => {
  axios
    .post('http://localhost:5039/api/Cottages/CottageList', {})
    .then((res) => {
      cottagesDatas.value = res.data.data;
    });
};

//获取栋舍下栏位信息http://localhost:5039/api/Cottages/SearchFields
const fieldsDatas: any = ref([]);
const getFields = (cottagesId: number, index: number) => {
  fieldsDatas.value[index] = [];
  const request: any = ref({});
  request.cottagesId = cottagesId;
  axios
    .post('http://localhost:5039/api/Cottages/SearchFields', request)
    .then((res) => {
      console.log(res.data.data);
      fieldsDatas.value[index] = res.data.data;
      loge.healthArray[index].field = '';
    });
};

//获取耳号下拉信息
const sleepInfoDatas: any = ref([]);
const getSleepInfos = () => {
  axios
    .get('http://localhost:5039/api/SleepBegin/ProBeginEarSearch')
    .then((res) => {
      console.log(res);
      sleepInfoDatas.value = res.data.data;
    });
};

//多选
// const multipleSelection = ref([])
// const handleSelectionChange = (val: any) => {
//   multipleSelection.value = val
//   console.log(multipleSelection.value)
// }

//全部保存
const allDomain = () => {
  try {
    loge.healthArray.forEach((c: any) => {
      if (
        c.sleepInforId == '' ||
        c.cottagesId == '' ||
        c.field == '' ||
        c.proBeginWeight == '' ||
        c.maleBeginSum == ''
      ) {
        ElMessage.error('还有信息未选择或填写,请再次检查！！！');
        throw new Error('End Loop');
      }
    });
  } catch (e) {
    e;
  }

  const request: any = ref({});
  request.datas = loge.healthArray[0];
  console.log(request.datas);
  axios
    .post('http://localhost:5039/api/SleepBegin/Handle/seedmaleAdd', request.datas)
    .then((res) => {
      console.log(res.data.data);
      if (res.data.code > 0) {
        ElMessage.success('添加成功');
        loge.healthArray.length = 0;
        router.push('/MaleBeginAdd');
      } else {
        ElMessage.error('添加失败，再试试！！');
      }
    });
};

onMounted(() => {
  getIds1();
  getIds2();
  getCottages();
  getSleepInfos();
});
</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

/* 设置第一行的 td 顶部边框加粗并设置为红色 */
table tr:first-child td {
  border-top: 3px solid red;
  /* 设置顶部边框为3px宽度的红色 */
  padding: 10px;
  text-align: center;
}

/* 设置 td 的样式 */

table td {
  padding: 10px;
  border: 1px solid #ccc;
  text-align: center;
  font-size: 14px;
  height: 60px;
  width: 150px;
  white-space: nowrap; /* 防止内容换行 */
}

/* 可选：为 table 添加样式 */
table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

/*______________________________________________________*/

.table-container {
  max-width: 100%;
  overflow-x: auto; /* 启用水平滚动 */
  margin: 20px 0; /* 设置容器的外边距 */
}
:deep(.el-input__wrapper) {
  box-shadow: none;
  text-align: center;
}

:deep(.el-select__wrapper) {
  box-shadow: none;
}
::v-deep(.center-input .el-input__inner) {
  text-align: center;
}
</style>
